<template>
	<view class="filter-popup">
		<!-- 城市头部，保持原有 -->
		<city-head></city-head>
		<!-- tabs 部分，保持原有 -->
		<z-tabs ref="tabsRef" scroll-count="1" :list="tabsList" :current="currentIndex" @change="handleTabChange"
			value-key="id" :active-style="{'font-size':'36rpx','font-weight':'bold','color': '#333333'}"
			:inactive-style="{'font-size':'28rpx','color': '#666666'}">
			<template slot="right">
				<view class="selectMore uni-flex uni-justify-between uni-align-center" @click="handleClose">
					<text class="text-group_10">筛选</text>
					<image class="more_img2" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}select_gray2.png`" />
				</view>
			</template>
		</z-tabs>

		<!-- 新增红色框内筛选内容 -->
		<view class="filter-content">
			<!-- 搜索框 -->
			<view class="search-box">
				<uni-icons type="search" size="28" color="#999999"></uni-icons>
				<input class="search-input" type="text" placeholder="搜索你想要的服务" v-model="searchValue" />
			</view>

			<!-- 距离滑块 -->
			<view class="distance-section">
				<text class="distance-label">距离</text>

				<view class="slider-item">
					<!-- <slider :min="0" :max="20" :value="distance" @change="handleDistanceChange" activeColor="#2F80ED"
						backgroundColor="#E0E0E0"  block-size="30"  /> -->

					<slider-range :value="nearDistance" :min="nearDistanceMin" :max="nearDistanceMax" 
						:bar-height="3" :block-size="26" background-color="#E0E0E0" active-color="#2F80ED"
						:format="format" :decorationVisible="true" @change="handleRangeChange"></slider-range>
				</view>
			</view>

			<!-- 结算标签 -->
			<view class="settle-section">
				<text class="related-label">结算</text>
				<view class="tags-wrap">
					<!-- 结单快标签：点击时判断是否取消 -->
					<label class="settle-tag" :class="{ active: selectedSettle === 'fast' }"
						@click="selectedSettle = selectedSettle === 'fast' ? '' : 'fast'">
						结单快
					</label>
					<!-- 结算率高标签：点击时判断是否取消 -->
					<label class="settle-tag" :class="{ active: selectedSettle === 'high' }"
						@click="selectedSettle = selectedSettle === 'high' ? '' : 'high'">
						结算率高
					</label>
				</view>
			</view>

			<!-- 与我相关标签 -->
			<view class="related-section" v-if="showRelatedTags">
				<text class="related-label">与我相关</text>
				<view class="tags-wrap">
					<label class="related-tag" v-for="tag in userServices" :key="tag.id">
						{{ tag.name }}
					</label>
				</view>
			</view>
			<view class="bottom-text-box">
				<text class='text1'>请添加您感兴趣的服务项目</text>
				<view class='text2' @click='goService'>去添加 <uni-icons type="right" size="11"
						color="#2F80ED"></uni-icons></view>
			</view>
		</view>

		<!-- 原有操作按钮区域，可根据需要调整逻辑 -->
		<view class="filter-actions">
			<button @click="handleReset" class="reaeat-button">重置</button>
			<button @click="handleConfirm" class="confirm-button">确定</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		defineProps,
		defineEmits,
		watch
	} from "vue";
	import cityHead from "@/components/city-head/index.vue";
	import SliderRange from '@/components/primewind-sliderrange/components/primewind-sliderrange/index.vue';

	// 定义接收的 props（必须包含 userServices，且类型为数组）
	const props = defineProps({
		tabsList: {
			type: Array,
			required: true
		},
		currentIndex: {
			type: Number,
			required: true
		},
		userServices: {
			type: Array,
			default: () => []
		} // 强制默认值为空数组
	});

	// 初始化状态变量（确保不为 undefined）
	const userServices = ref([]); // 存储从 props 同步的服务项
	const showRelatedTags = ref(false); // 控制标签区域显示

	// 监听 props.userServices 变化，同步数据并控制显示
	watch(
		() => props.userServices,
		(newVal) => {
			// 容错处理：确保 newVal 是数组
			const validServices = Array.isArray(newVal) ? newVal : [];
			userServices.value = validServices;
			showRelatedTags.value = validServices.length > 0; // 有服务项则显示标签区域
		}, {
			immediate: true
		} // 初始加载时执行一次
	);

	// 其他状态变量
	const nearDistanceMin = ref(0);
	const nearDistanceMax = ref(20);
	const searchValue = ref('');
	const nearDistance = ref([0, 20]);
	const selectedSettle = ref('');
	const selectedRelated = ref([]);
	// 添加结算相关参数
	const closeQuickly = ref(0); // 结单快参数
	const closeRateMax = ref(0); // 结算率高参数

	// 定义事件
	const emit = defineEmits(['tabChange', 'close', 'confirm', 'reset']);

	// 其他方法（handleRangeChange、toggleRelated、handleConfirm 等保持不变）
	const format = (val) => val + 'km';
	const handleRangeChange = (e) => {
		nearDistance.value = e;
	};
	const handleTabChange = (index, id) => {
		emit('tabChange', index, id);
	};
	// 切换标签选中状态
	// const toggleRelated = (tagId) => {
	// 	const index = selectedRelated.value.indexOf(tagId);
	// 	if (index > -1) {
	// 		selectedRelated.value.splice(index, 1);
	// 	} else {
	// 		selectedRelated.value.push(tagId);
	// 	}
	// };
	const handleClose = () => {
		emit('close');
	};
	const handleReset = () => {
		// 原有重置逻辑
		searchValue.value = '';
		nearDistance.value = [0, 20];
		selectedSettle.value = '';
		closeQuickly.value = 0;
		closeRateMax.value = 0;

		// 新增：清除与我相关标签的本地数据
		selectedRelated.value = []; // 清空选中的服务项ID
		userServices.value = []; // 清空显示的服务项列表
		showRelatedTags.value = false; // 隐藏标签区域

		// 通知父组件重置（可选，根据父组件逻辑调整）
		emit('reset', {
			needResetUserServices: true
		});
		handleClose();
	};
	const handleConfirm = () => {
		// 根据选中的标签设置对应的参数
		closeQuickly.value = selectedSettle.value === 'fast' ? 1 : 0;
		closeRateMax.value = selectedSettle.value === 'high' ? 1 : 0;

		const filterParams = {
			jobName: searchValue.value,
			nearDistance: nearDistance.value,
			serviceItem: selectedRelated.value.join(','),
			closeQuickly: closeQuickly.value, // 添加结单快参数
			closeRateMax: closeRateMax.value // 添加结算率高参数
		};

		emit('confirm', filterParams);
		handleClose(); // 确认后关闭弹窗
	};
	const clearUserServices = () => {
		userServices.value = [];
		selectedRelated.value = [];
		showRelatedTags.value = false;
	};

	// 暴露方法供父组件调用
	defineExpose({
		clearUserServices
	});
	// 打开 addService 页面时传递事件通道
	const goService = () => {
		uni.navigateTo({
			url: '/pages/contract/addService',
			events: {
				// 监听子页面返回的数据
				updateSelectedServices: (data) => {
					userServices.value = data.selectedServices;
					showRelatedTags.value = data.selectedServices.length > 0;
					// 存储 serviceItemIds（用于请求接口）
					selectedRelated.value = data.serviceItemIds.split(','); // 转为数组，方便后续处理
				}
			}
		});
	};
</script>

<style lang="scss" scoped>
	.filter-popup {
		background-color: #fff;
		padding: 20rpx 0rpx;
		border-bottom-left-radius: 50rpx;
		border-bottom-right-radius: 50rpx;
	}

	.filter-content {
		padding: 20rpx;

		.bottom-text-box {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 35rpx;

			.text1 {
				font-size: 24rpx;
				color: #999;
				font-weight: 400;
				margin-right: 20rpx;
			}

			.text2 {
				color: #2F80ED;
				font-size: 24rpx;
				font-weight: 400;
			}
		}
	}

	.search-box {
		display: flex;
		align-items: center;
		background-color: #f1f1f1;
		border-radius: 36rpx;
		padding: 10rpx 20rpx;
		margin-bottom: 20rpx;

		.search-icon {
			margin-right: 10rpx;
		}

		.search-input {
			flex: 1;
			font-size: 28rpx;
		}
	}

	.distance-section {
		margin-bottom: 30rpx;
		height: 150rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.distance-label {
			font-size: 28rpx;
			display: block;
			font-weight: 500;
			color: #333;
		}

		.distance-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0rpx 10rpx;

		}

	}

	.settle-section {
		margin-bottom: 20rpx;

		.related-label {
			font-size: 28rpx;
			margin-bottom: 10rpx;
			color: #333;
			font-weight: 500;
			display: block;
		}

		.tags-wrap {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.settle-tag {
				padding: 10rpx 20rpx;
				background-color: #f1f1f1;
				border-radius: 6rpx;
				font-size: 24rpx;
				cursor: pointer;
				color: #333;
				font-weight: 400;

				&.active {
					background-color: #2F80ED;
					color: #fff;
				}
			}
		}
	}

	.related-section {
		margin-bottom: 20rpx;

		.related-label {
			font-size: 28rpx;
			margin-bottom: 10rpx;
			display: block;
			color: #333;
			font-weight: 500;
		}

		.tags-wrap {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.related-tag {
				padding: 10rpx 20rpx;
				background-color: #f1f1f1;
				border-radius: 6rpx;
				font-size: 24rpx;
				cursor: pointer;
				color: #333;
				font-weight: 400;

				&.active {
					background-color: #2F80ED;
					color: #fff;
				}
			}
		}
	}

	.filter-actions {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0rpx;

		.reaeat-button {
			height: 88rpx;
			border-radius: 44rpx;
			background-color: #999;
			color: #fff;
			font-size: 30rpx;
			font-weight: 500;
			padding: 10rpx 130rpx;
			box-sizing: border-box;
		}

		.confirm-button {
			height: 88rpx;
			border-radius: 44rpx;
			background: #2F80ED;
			color: #fff;
			font-size: 30rpx;
			font-weight: 500;
			padding: 10rpx 130rpx;
			box-sizing: border-box;
		}
	}

	.selectMore {
		width: 80rpx;
		font-weight: 500;
		font-size: 28rpx;
		color: #666666;
		padding: 0 25rpx;

		.more_img2 {
			width: 16rpx;
			height: 16rpx;
			margin-top: 6rpx;
		}
	}

	.demo-slider-range {
		background-color: #fff;
		padding: 100rpx 40rpx 0;
	}

	.section-title {
		padding: 0 0 20rpx;
		color: #666;
	}

	.slider-item:not(:last-child) {
		margin-bottom: 100rpx;
	}
</style>